<template>
    <div class="body_">
        <div class="centered">
            <div style="width: 350px; margin: 150px auto">
                <div style="color: lightskyblue; font-size: 20px; padding: 30px 0">
                    <span class="set_back_to">
                        <a href="#/setup" style="text-decoration: none;">&lt;</a>
                    </span>
                    <span class="change">修改密码</span> 
                </div>
                <el-form ref="form" :model="form" size="normal" :rules="rules">
                    <el-form-item label="旧密码" prop="oldPassword">
                        <el-input type="password" v-model="form.oldPassword"></el-input>
                    </el-form-item>
                    <el-form-item label="新密码" prop="newPassword">
                        <el-input type="password" v-model="form.newPassword"></el-input>
                    </el-form-item>
                    <el-form-item label="确认密码" prop="confirmPassword">
                        <el-input type="password" v-model="form.confirmPassword"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <div style="display: flex">
                            <el-input v-model="form.validCode" style="width: 60%;" placeholder="请输入验证码"></el-input>
                            <ValidCode @input="createValidCode" />
                        </div>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" style="width: 100%" @click="updatepwd">确认修改</el-button>
                    </el-form-item>
                    <el-form-item>
                        <el-button style="width: 100%" @click="gotoRegister">返回首页</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>
    </div>
</template>
  
<script>
import { jwtDecode } from 'jwt-decode';
import ValidCode from "@/views/login/ValidCode.vue";
export default {
    name: "Login",
    components: {
        ValidCode
    },
    name: 'LoginView',
    data() {
        return {
            form: {
                oldPassword: '',
                newPassword: '',
                confirmPassword: ''
            },
            rules: {
                oldPassword: [
                    { required: true, message: '请输入旧密码', trigger: 'blur' }
                ],
                newPassword: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    {
                        type: 'string', message: '请输入不包含空格的字符', trigger: 'blur', transform(value) {
                            if (value && value.indexOf(' ') === -1) {
                                return value
                            } else {
                                return false
                            }
                        }
                    },
                    {
                        trigger: 'blur', validator: (rule, value, callback) => {
                            var passwordreg = /(?=.*\d)(?=.*[a-zA-Z])(?=.*[^a-zA-Z0-9]).{6,10}/
                            if (!passwordreg.test(value)) {
                                callback(new Error('密码必须由数字、字母、特殊字符组合,请输入6-10位'))
                            } else {
                                callback()
                            }
                        }
                    }
                ],
                confirmPassword: [
                    { required: true, message: '请确认新密码', trigger: 'blur' },
                    { validator: this.checkNewPassword, trigger: 'blur' }
                ],

            },
            validCode: '',
            Admin: {
                phone: '',
                password: ''
            },
        };
    },
    methods: {
        checkNewPassword(rule, value, callback) {
            if (value !== this.form.newPassword) {
                callback(new Error('两次输入的密码不一致'));
            } else {
                callback();
            }
        },
        createValidCode(data) {
            this.validCode = data
        },
        gotoRegister() {
            // 跳转注册页面
            this.$router.push('/index');
        },
        updatepwd() {
            this.$refs['form'].validate((valid) => {
                if (valid) {
                    if (!this.form.validCode) {
                        this.$message.error("请填写验证码")
                        return
                    }
                    if (this.form.validCode.toLowerCase() !== this.validCode.toLowerCase()) {
                        this.$message.error("验证码错误")
                        return
                    }
                    this.handleSave();
                }
            });
        },
        handleSave() {
            const jwt = localStorage.getItem('jwt');
            if (jwt) {
                const decoded = jwtDecode(jwt);
                const userId = decoded.id; // 确保你的token结构中有id字段
                const oldPassword = this.form.oldPassword;
                const newPassword = this.form.newPassword;
                this.$http.post('/api/students/studentChange-password', { userId, oldPassword, newPassword }, {
                    headers: {
                        'Content-Type': 'application/json'
                    }
                })
                    .then(response => {
                        if (response.data.code == 1) {
                            this.$message.success("修改成功，请重新登录");
                            localStorage.removeItem('jwt');
                            this.$router.push('/login');
                        }
                        if (response.data.code == 0) {
                            this.$message.error(response.data.data);
                        }
                    }).catch(() => {
                        this.$message.error("请求错误");
                    });

            }
        },
    },
    mounted() {

    },
};
</script>
  
<style>
@import "@/style/login.css";
</style>